package zj.it.bhne.gridengineeringsurvey.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.dialog.widget.NormalDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.File;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.activity.AddItemActivity;
import zj.it.bhne.gridengineeringsurvey.activity.DetailsActivity;
import zj.it.bhne.gridengineeringsurvey.activity.MapActivity;
import zj.it.bhne.gridengineeringsurvey.activity.OnlineDetailsActivity;
import zj.it.bhne.gridengineeringsurvey.entity.Filter;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Equipment;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Items;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Line;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Online;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Photos;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Points;
import zj.it.bhne.gridengineeringsurvey.myutils.ExportUnit;
import zj.it.bhne.gridengineeringsurvey.myutils.GetToken;
import zj.it.bhne.gridengineeringsurvey.myutils.HttpConfig;
import zj.it.bhne.gridengineeringsurvey.myutils.MyUtils;
import zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager;
import zj.it.bhne.gridengineeringsurvey.myutils.ZipUtils;
import zj.it.bhne.gridengineeringsurvey.myutils.filter.FiltrateBean;
import zj.it.bhne.gridengineeringsurvey.myutils.filter.FlowPopWindow;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.EquipmentDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.ItemsDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.LineDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.OnlineDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PhotosDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PointsDao;

import static java.util.Objects.requireNonNull;
import static zj.it.bhne.gridengineeringsurvey.fragment.OneFragment.deleteDir;
import static zj.it.bhne.gridengineeringsurvey.fragment.OneFragment.parseXMLWithPulls;
import static zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager.getThreadPool;

/**
 * 项目首页中BottomActivity的第二个页面
 */
public class TwoFragment extends Fragment implements View.OnClickListener {


    private final List<View> views = new ArrayList<>();
    private final Handler handler = new Handler();
    private final List<Items> listItems1 = new ArrayList<>();
    private SmartRefreshLayout refreshLayout;
    private SmartRefreshLayout local_refreshLayout;
    private List<Online> onlines = new ArrayList<>();
    private Button two_local;
    private Button two_online;
    private ViewPager two_viewPager;
    private ListView two_listView;
    private List<Items> list = new ArrayList<>();
    private MainAdapter adapter;
    private TextView online_tv_name;
    private RecyclerView listView;
    private boolean DIALOG_BOTTOM = true;
    private LinearLayout two_linear;
    private CheckBox two_cb_check;
    private Button two_btn_delete, two_btn_daochu, two_btn_shangchuan;
    private ImageButton two_ib_search;
    private EditText two_editText;
    private FlowPopWindow flowPopWindow;
    private List<FiltrateBean> dictList = new ArrayList<>();
    private TextView activity_tv_save;
    private ProgressDialog mProgressDialog;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            //若工作完成，取消动画，初始化界面
            if (msg.what == 1)
                mProgressDialog.cancel();
            /*//开始初始化界面
            initView();*/
        }
    };
    private Runnable mRunnable = () -> {
        /*
            需要耗时的工作
        */
        delete();
        initData();
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessage(msg);
    };
    private ThreadManager.ThreadPool threadPool;
    private CommonAdapter recycleAdapter;


    /**
     * 创建ProrgressDialog
     */
    private void createProgressDialog() {
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setMessage("删除数据中,请稍等...");
        mProgressDialog.show();
    }


    //用Pull方式解析XML
    private List<Online> parseXMLWithPull(String xmlData) {
        onlines.clear();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            //设置输入的内容
            xmlPullParser.setInput(new StringReader(xmlData));
            //获取当前解析事件，返回的是数字
            int eventType = xmlPullParser.getEventType();
            //保存内容
            //勘测任务主键
            String id = null;
            //勘测任务关联项目id
            String projectid = null;
            //勘测任务关联项目id
            String projectName = null;
            //负责人
            String fzr = null;
            //配合人
            String phr = null;
            //负责人Id
            String fzrId = null;
            //配合人id
            String phrId = null;
            //状态
            String state = null;
            //备注
            String description = null;
            //删除标志位
            String isdel = null;
            //创建时间
            String createtime = null;
            //创建人
            String createuser = null;
            //现场勘测时间
            String xckctime = null;
            while (eventType != (XmlPullParser.END_DOCUMENT)) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    //开始解析XML
                    case XmlPullParser.START_TAG: {
                        //nextText()用于获取结点内的具体内容
                        if ("Id".equals(nodeName)) {
                            id = xmlPullParser.nextText();
                        }
                        if ("Projectid".equals(nodeName)) {
                            projectid = xmlPullParser.nextText();
                        }
                        if ("ProjectName".equals(nodeName)) {
                            projectName = xmlPullParser.nextText();
                        }
                        if ("fzr".equals(nodeName)) {
                            fzr = xmlPullParser.nextText();
                        }
                        if ("phr".equals(nodeName)) {
                            phr = xmlPullParser.nextText();
                        }
                        if ("state".equals(nodeName)) {
                            state = xmlPullParser.nextText();
                        }
                        if ("description".equals(nodeName)) {
                            description = xmlPullParser.nextText();
                        }
                        if ("Isdel".equals(nodeName)) {
                            isdel = xmlPullParser.nextText();
                        }
                        if ("createtime".equals(nodeName)) {
                            createtime = xmlPullParser.nextText();
                        }
                        if ("createuser".equals(nodeName)) {
                            createuser = xmlPullParser.nextText();
                        }
                        if ("xckctime".equals(nodeName)) {
                            xckctime = xmlPullParser.nextText();
                        }
                        if ("phrid".equals(nodeName)) {
                            fzrId = xmlPullParser.nextText();
                        }
                        if ("fzrid".equals(nodeName)) {
                            phrId = xmlPullParser.nextText();
                        }
                    }
                    break;
                    //结束解析
                    case XmlPullParser.END_TAG: {

                        if (id != null && projectid != null) {

                            if (!getList(id)) {
                                online_tv_name.setVisibility(View.GONE);
                                Online online = new Online();
                                online.setCid(null);
                                online.setId(id);
                                online.setProjectid(projectid);
                                online.setFzr(fzr);
                                online.setPhr(SPUtils.getInstance().getString("usersId"));
                                online.setState(state);
                                online.setDescription(projectName);
                                online.setName(description);
                                online.setIsdel(isdel);
                                //online.setCreatetime(TimeUtils.millis2String(TimeUtils.string2Millis(createtime),format));
                                online.setCreatetime(TimeUtils.millis2String(Long.parseLong(createtime), format));
                                online.setCreateuser(createuser);
                                online.setXckctime(xckctime);
                                online.setDown("no");
                                online.setPhrId(phrId);
                                online.setFzrId(fzrId);
                                MyApplication.getInstances().getOnlineDao().insert(online);
                                //onlines.add(online);
                                //MyApplication.getInstances().getOnlineDao().insert(online);
                                onlines = MyApplication.getInstances().getOnlineDao().queryBuilder().where(OnlineDao.Properties.Phr.eq(SPUtils.getInstance().getString("usersId"))).build().list();

                            } else {
                                //onLoad();
                                MyUtils.getToast(getContext(), "没有更新");
                            }
                        }
                    }
                    break;
                    default:
                        break;
                }
                //下一个
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (onlines.size() > 0) {
            //Log.e("TAG", "parseXMLWithPull: " + onlines.size());
            return onlines;
        } else {
            //Log.e("TAG", "parseXMLWithPullsss: " + MyApplication.getInstances().getOnlineDao().queryBuilder().where(OnlineDao.Properties.Phr.eq(SPUtils.getInstance().getString("usersId"))).build().list().size());
            return MyApplication.getInstances().getOnlineDao().queryBuilder().where(OnlineDao.Properties.Phr.eq(SPUtils.getInstance().getString("usersId"))).build().list();
        }
    }

    /**
     * @param id 获取当前获取到的项目id
     * @return 返回数据库中是否已经存在此条信息
     */
    private boolean getList(String id) {
        List<Online> list = MyApplication.getInstances().getOnlineDao().queryBuilder().build().list();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId().equals(id)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取数据库中存储的项目信息
     **/
    private void initData() {
        try {
            list = MyApplication.getInstances().getItemsDao().queryBuilder().orderDesc(ItemsDao.Properties.Id).build().list();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initDialog() {
        two_cb_check.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setBatchCheck(1);
                    MyApplication.getInstances().getItemsDao().update(list.get(i));
                }
                adapter.notifyDataSetChanged();
            }

            if (!isChecked) {
                for (int i = 0; i < list.size(); i++) {
                    //这如果使用第一种方法会修改不了数据，也不尝试全使用这个了，等有时间了试试。
                    list.get(i).setBatchCheck(0);
                    MyApplication.getInstances().getItemsDao().update(list.get(i));
                }
                adapter.notifyDataSetChanged();
            }
        });
        two_btn_delete.setOnClickListener(v -> {
            createProgressDialog();
            threadPool.execute(mRunnable);

            adapter.notifyDataSetChanged();
        });
        two_btn_daochu.setOnClickListener(v -> {
            initData();
            List<Items> itemsList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getBatchCheck() == 1) {
                    itemsList.add(list.get(i));
                } else {
                    MyUtils.getToast(getContext(), "没有选中项目");
                }
            }
            if (itemsList.size() == 1) {
                ExportUnit exportUnit = new ExportUnit();
                exportUnit.SetLocalExport(getContext(), itemsList.get(0).getId(), itemsList.get(0).getName());
            } else {

                List<File> fileList = new ArrayList<>();
                List<File> filePath = new ArrayList<>();
               /* File[] paths = new File[0];
                File[] filePaths = new File[0];*/
                for (int j = 0; j < itemsList.size(); j++) {
                    /*paths[j] = ExportUnit.getXmlFile(getContext(), itemsList.get(j).getId(), itemsList.get(j).getName());
                    filePaths[j] = new File(itemsList.get(j).getName());*/
                    ExportUnit exportUnit = new ExportUnit();
                    filePath.add(exportUnit.getXmlFile(getContext(), itemsList.get(j).getId(), itemsList.get(j).getName()));
                    fileList.add(new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/bhne/" + itemsList.get(j).getName()));
                }

                if (itemsList.size() > 0)
                    startZip(filePath, fileList, itemsList.get(0).getName() + "...");
                else
                    ToastUtils.showShort("请选择项目");
            }
        });
        two_btn_shangchuan.setOnClickListener(v -> {
            initData();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getBatchCheck() == 1) {
                    MyUtils.getToast(getContext(), "上传成功");
                } else {
                    MyUtils.getToast(getContext(), "没有选中项目");
                }
            }
        });
    }

    private void delete() {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getBatchCheck() == 1) {
                //删除所有相关联的数据
                MyApplication.getInstances().getItemsDao().deleteByKey(list.get(i).getId());
                List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(list.get(i).getId())).build().list();
                for (int j = 0; j < pointsList.size(); j++) {
                    MyApplication.getInstances().getPointsDao().delete(pointsList.get(j));
                    List<Equipment> equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(pointsList.get(j).getId())).build().list();
                    if (equipmentList.size() > 0)
                        for (int f = 0; f < equipmentList.size(); f++) {
                            MyApplication.getInstances().getEquipmentDao().delete(equipmentList.get(f));
                        }
                    List<Photos> photosList = MyApplication.getInstances().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(pointsList.get(j).getId())).build().list();
                    if (photosList.size() > 0)
                        for (int z = 0; z < photosList.size(); z++) {
                            MyApplication.getInstances().getPhotosDao().delete(photosList.get(z));
                        }
                }
                List<Line> lines = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(list.get(i).getId())).build().list();
                for (int z = 0; z < lines.size(); z++) {
                    MyApplication.getInstances().getLineDao().delete(lines.get(z));
                }
                try {
                    deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/bhne/" + list.get(i).getName());
                    deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/bhne/" + list.get(i).getName() + ".zip");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * 批量导出信息对话框以及实现
     */
    private void startZip(final List<File> paths, final List<File> filePaths, final String name) {
        @SuppressLint("InflateParams") View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_add_concealed_dialog, null);
        Button alertSureTv = view.findViewById(R.id.add_sure);
        Button alertCancelTv = view.findViewById(R.id.add_cancle);
        CheckBox alertCheckBox = view.findViewById(R.id.add_cb);

        //显示确认框
        AlertDialog mAlertDialog = new AlertDialog.Builder(Objects.requireNonNull(getContext())).setView(view).create();
        mAlertDialog.show();

        //取消
        alertSureTv.setOnClickListener(view1 -> mAlertDialog.cancel());
        //导出
        alertCancelTv.setOnClickListener(view12 -> {
            if (alertCheckBox.isChecked()) {
                ZipUtils.zipFiles(filePaths, Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + name + "Mul" + ".zip");
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + name + "Mul" + ".zip");
                startIntent(file);
            } else {
                ZipUtils.zipFiles(paths, Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + name + "No" + ".zip");
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + name + "No" + ".zip");
                startIntent(file);
            }
            mAlertDialog.cancel();
        });


    }

    /**
     * 分享文件
     */
    private void startIntent(File file) {
        if (file != null) {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //做一些处理
                shareIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(Objects.requireNonNull(getContext()), "zj.it.bhne.gridengineeringsurvey.fileprovider", file));
                shareIntent.setType("text/plain");

                //设置分享列表的标题，并且每次都显示分享列表
                getContext().startActivity(Intent.createChooser(shareIntent, "分享到"));


            } else {
                //在版本低于此的时候，做一些处理
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
                shareIntent.setType("text/plain");

                //设置分享列表的标题，并且每次都显示分享列表
                Objects.requireNonNull(getContext()).startActivity(Intent.createChooser(shareIntent, "分享到"));
            }

        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_two, container, false);
        initView(view);
        return view;
    }

    @SuppressLint("InflateParams")
    private void initView(final View view) {
        threadPool = getThreadPool();
        two_local = view.findViewById(R.id.two_local);
        two_local.setOnClickListener(this);
        two_online = view.findViewById(R.id.two_online);
        two_online.setOnClickListener(this);
        two_viewPager = view.findViewById(R.id.two_viewPager);
        two_viewPager.setOnClickListener(this);
        View view1 = LayoutInflater.from(getContext()).inflate(R.layout.fragment_local, null);
        View view2 = LayoutInflater.from(getContext()).inflate(R.layout.fragment_online, null);
        views.add(view1);
        views.add(view2);
        two_editText = view.findViewById(R.id.two_editText);
        setViewPager();
        two_listView = view1.findViewById(R.id.two_listView);
        TextView two_tv_name = view1.findViewById(R.id.two_tv_name);
        two_linear = view1.findViewById(R.id.local_linear);
        two_cb_check = view1.findViewById(R.id.two_cb_check);
        two_btn_delete = view1.findViewById(R.id.two_btn_delete);
        two_btn_daochu = view1.findViewById(R.id.two_btn_daochu);
        two_btn_shangchuan = view1.findViewById(R.id.two_btn_shangchuan);
        local_refreshLayout = view1.findViewById(R.id.local_refreshLayout);
        initData();
        listOnClick();
        if (list.size() > 0) {
            adapter = new MainAdapter(getContext(), list);
            two_listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            two_tv_name.setVisibility(View.GONE);
        } else {
            two_tv_name.setVisibility(View.VISIBLE);
        }

        setLocalRefresh();

        online_tv_name = view2.findViewById(R.id.online_tv_name);
        listView = view2.findViewById(R.id.two_listViews);
        refreshLayout = view2.findViewById(R.id.refreshLayout);


        setRecycleView(getContext(), MyApplication.getInstances().getOnlineDao().queryBuilder().where(OnlineDao.Properties.Phr.eq(SPUtils.getInstance().getString("usersId"))).list());
        //listView.setAdapter(mainAdapter);

        requireNonNull(getActivity()).supportInvalidateOptionsMenu();


        //实时监测EditText的输入情况
        monitoringEditText();


        TextView two_zonghe = view.findViewById(R.id.two_zonghe);
        two_zonghe.setOnClickListener(this);
        TextView two_shijian = view.findViewById(R.id.two_shijian);
        two_shijian.setOnClickListener(this);
        two_ib_search = view.findViewById(R.id.two_ib_search);
        two_ib_search.setOnClickListener(this);

        //添加筛选框的数据
        initParam();

        //添加筛选框
        addFilter(view);


        ImageButton activity_ib_back = view.findViewById(R.id.activity_ib_back);
        TextView activity_tv_title = view.findViewById(R.id.activity_tv_title);
        activity_tv_save = view.findViewById(R.id.activity_tv_save);
        activity_tv_save.setOnClickListener(this);
        ImageView activity_iv_add = view.findViewById(R.id.activity_iv_add);
        activity_iv_add.setOnClickListener(this);
        activity_ib_back.setVisibility(View.GONE);
        activity_tv_title.setText(getString(R.string.bottom_two));

    }

    /**
     * 本地刷新
     */
    private void setLocalRefresh() {
        local_refreshLayout.setEnableLoadMore(false);
        local_refreshLayout.setOnRefreshListener(refreshment -> {
            Long start = System.currentTimeMillis();
            list = MyApplication.getInstances().getItemsDao().queryBuilder().orderDesc(ItemsDao.Properties.Id).build().list();
            adapter = new MainAdapter(getContext(), list);
            two_listView.setAdapter(adapter);
            Long stop = System.currentTimeMillis() - start;
            refreshment.finishRefresh(stop.intValue());
        });
    }

    /**
     * 设置viewpager
     */
    private void setViewPager() {
        two_viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return 2;
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                View view3 = views.get(position);
                container.addView(view3);
                return view3;
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(views.get(position));
            }

        });
        try {
            two_viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    if (position == 0) {
                        two_editText.setText("");
                        two_editText.setText("");
                        two_local.setTextColor(Color.rgb(255, 255, 255));
                        two_online.setTextColor(Color.rgb(51, 51, 51));
                        two_local.setBackgroundResource(R.drawable.btn_shape);
                        two_online.setBackgroundResource(R.drawable.btn_shape_white);
                        try {
                            adapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        two_editText.setText("");
                        two_editText.setText("");
                        two_online.setTextColor(Color.rgb(255, 255, 255));
                        two_local.setTextColor(Color.rgb(51, 51, 51));
                        two_local.setBackgroundResource(R.drawable.btn_shape_white);
                        two_online.setBackgroundResource(R.drawable.btn_shape);
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测输入框输入状况
     */
    private void monitoringEditText() {
        two_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if ("".contentEquals(s)) {
                    two_ib_search.setVisibility(View.GONE);
                    try {
                        adapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    two_ib_search.setVisibility(View.VISIBLE);
                }

                String aa = s.toString();
                Pattern p = Pattern.compile(aa);
                if (two_viewPager.getCurrentItem() == 0) {
                    listItems1.clear();
                    for (int i = 0; i < list.size(); i++) {
                        Items pmi = list.get(i);
                        String pmiTitle = pmi.getName();
                        Matcher matcher = p.matcher(pmiTitle);

                        if (matcher.find()) {
                            listItems1.add(pmi);
                        }
                    }


                } /*else {
                    listItems.clear();
                    for (int i = 0; i < onlines.size(); i++) {
                        Online pmi = onlines.get(i);
                        String pmiTitle = pmi.getDescription();
                        Matcher matcher = p.matcher(pmiTitle);

                        if (matcher.find()) {
                            listItems.add(pmi);
                        }
                    }

                }*/


            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        two_editText.setOnEditorActionListener((v, actionId, event) -> {

            if (two_viewPager.getCurrentItem() == 0) {
                MainAdapter mainAdapter1 = new MainAdapter(getContext(), listItems1);

                two_listView.setAdapter(mainAdapter1);
                ////Log.e("TAG", "onClick: " + listItems1.size());
            } /*else {
                //MainsAdapter mainAdapter2 = new MainsAdapter(getContext(), listItems);

                //listView.setAdapter(mainAdapter2);
            }*/


            return false;
        });
    }

    /**
     * 添加筛选框
     */
    private void addFilter(View view) {
        final LinearLayout shaixuan = view.findViewById(R.id.two_shaixuan);
        shaixuan.setOnClickListener(view32 -> {
            flowPopWindow = new FlowPopWindow(getActivity(), dictList);
            flowPopWindow.showAsDropDown(shaixuan);
            final List<Filter> filter = new ArrayList<>();
            filter.clear();
            flowPopWindow.setOnConfirmClickListener(() -> {
                for (FiltrateBean fb : dictList) {
                    List<FiltrateBean.Children> cdList = fb.getChildren();
                    for (int x = 0; x < cdList.size(); x++) {
                        FiltrateBean.Children children = cdList.get(x);
                        if (children.isSelected()) {
                            filter.add(new Filter(fb.getTypeName(), children.getValue()));
                        }
                    }
                }
                List<Items> itemsList = new ArrayList<>();
                if (filter.size() > 0) {
                    for (int i = 0; i < filter.size(); i++) {
                        if ("获取方式".equals(filter.get(i).getName())) {
                            itemsList.clear();
                            for (int j = 0; j < list.size(); j++) {
                                if (list.get(j).getState().equals(filter.get(i).getValue())) {
                                    itemsList.add(list.get(j));
                                }
                            }
                        }
                        if ("建设类型".equals(filter.get(i).getName())) {
                            itemsList.clear();
                            for (int j = 0; j < list.size(); j++) {
                                if (list.get(j).getType().equals(filter.get(i).getValue())) {
                                    itemsList.add(list.get(j));
                                }
                            }
                        }
                        if ("电压等级".equals(filter.get(i).getName())) {
                            itemsList.clear();
                            for (int j = 0; j < list.size(); j++) {
                                if (list.get(j).getVoltage().equals(filter.get(i).getValue())) {
                                    itemsList.add(list.get(j));
                                }
                            }
                        }
                        /*if ("时间先后".equals(filter.get(i).getName())) {
                            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            Calendar c = Calendar.getInstance();
                            c.add(Calendar.DATE, -7);
                            Date monday = c.getTime();
                            String preMonday = sdf.format(monday);
                            for (int j = 0; j < list.size(); j++) {
                                if (MyUtils.isDateOneBigger(list.get(j).getTime(), preMonday)) {
                                    itemsList.add(list.get(j));
                                }
                            }
                            //MyUtils.getToast(getContext(), preMonday);
                        }*/
                        MainAdapter mainAdapter1 = new MainAdapter(getContext(), itemsList);
                        two_listView.setAdapter(mainAdapter1);
                    }
                }
            });

        });
    }

    /**
     * 设置在线项目
     *
     * @param context 上下文
     * @param onlines 列表数据
     */
    private void setRecycleView(Context context, List<Online> onlines) {
        if (onlines.size() > 0) {
            online_tv_name.setVisibility(View.GONE);
        } else
            online_tv_name.setVisibility(View.VISIBLE);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        listView.setLayoutManager(linearLayoutManager);

        setAdapter(context, onlines);
        listView.setAdapter(recycleAdapter);

        setRefresh();
    }

    private void setAdapter(Context context, List<Online> onlines) {
        recycleAdapter = new CommonAdapter<Online>(context, R.layout.activity_list, onlines) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void convert(ViewHolder holder, Online items, int position) {
                TextView one = holder.getView(R.id.one);
                TextView two = holder.getView(R.id.two);
                TextView three = holder.getView(R.id.three);
                Button imageButton = holder.getView(R.id.online_ib_down);

                one.setText(items.getDescription() + "");
                two.setText(items.getId() + " ");
                three.setText(items.getCreatetime());
                if (items.getDown().equals("yes")) {
                    imageButton.setText("已下载");
                } else {
                    imageButton.setText("下载");
                }

                //vieHolder.imageButton.setCurrentText("下载");
                imageButton.setOnClickListener(v -> {
                    items.setDown("yes");
                    MyApplication.getInstances().getOnlineDao().update(items);
                    List<Items> itemslist = MyApplication.getInstances().getItemsDao().queryBuilder().where(ItemsDao.Properties.Type.eq(items.getId())).list();
                    if (itemslist.size() > 0) {
                        ToastUtils.showShort("项目已存在，不可重复下载");
                    } else {
                        setDown(imageButton, items);
                    }
                });
            }
        };
    }


    /**
     * 下载在线项目
     *
     * @param imageButton v
     * @param items       临时保存
     */
    private void setDown(Button imageButton, Online items) {
        final Items item = new Items();
        imageButton.setText("下载中");
        item.setId(null);
        item.setName(items.getDescription());
        item.setNote(items.getPhr());
        item.setTime(items.getCreatetime());
        item.setIsCheck(false);
        item.setState("在线");
        item.setStop("0");
        item.setVoltage(items.getFzr());
        item.setType(items.getId() + "");
        item.setProjectId(items.getId());
        Runnable runnable = () -> {
            if (MyApplication.getInstances().getItemsDao().insert(item) > 0) {
                handler.postDelayed(() -> imageButton.setText("已下载"), 1500);
            } else {
                MyUtils.getToast(getContext(), "创建失败");
            }
        };
        ThreadManager.ThreadPool threadPool = getThreadPool();
        threadPool.execute(runnable);

    }


    /**
     * 下拉刷新
     */
    private void setRefresh() {
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshment -> {

            Long start = System.currentTimeMillis();
            if (MyApplication.getInstances().IsLogin()) {
                if (NetworkUtils.isConnected()) {
                    if (GetToken.getInstance().getToken()) {
                        refresh();
                        Long stop = System.currentTimeMillis() - start;
                        refreshment.finishRefresh(stop.intValue());
                    } else {
                        GetToken.getInstance().setToken();
                        refresh();
                        Long stop = System.currentTimeMillis() - start;
                        refreshment.finishRefresh(stop.intValue());
                    }
                } else {
                    ToastUtils.showShort("网络无连接");
                    Long stop = System.currentTimeMillis() - start;
                    refreshment.finishRefresh(stop.intValue(), false);
                }
            } else {
                ToastUtils.showShort("当前未登录");
                Long stop = System.currentTimeMillis() - start;
                refreshment.finishRefresh(stop.intValue());
            }

        });

    }

    private void refresh() {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        map.put("userid", SPUtils.getInstance().getString("usersId"));
        String result = HttpConfig.callService("getDataSurveyTask", map);
        List<Online> onlineList = parseXMLWithPull(result);
        if (onlineList.size() > 0) {
            online_tv_name.setVisibility(View.GONE);
        } else
            online_tv_name.setVisibility(View.VISIBLE);
        setAdapter(getContext(), onlineList);
        listView.setAdapter(recycleAdapter);
    }


    /**
     * 添加筛选框的数据
     */
    private void initParam() {
        String[] sexs = {"本地", "在线"};
        String[] colors = {"新建", "原有", "改造"};
        String[] company = {"交流20kv", "交流10kv", "交流5kv"};
        String[] times = {"最近三天", "最近一周", "最近一月"};

        FiltrateBean fb1 = new FiltrateBean();
        fb1.setTypeName("获取方式");
        List<FiltrateBean.Children> childrenList = new ArrayList<>();
        for (String sex : sexs) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(sex);
            childrenList.add(cd);
        }
        fb1.setChildren(childrenList);

        FiltrateBean fb2 = new FiltrateBean();
        fb2.setTypeName("建设类型");
        List<FiltrateBean.Children> childrenList2 = new ArrayList<>();
        for (String color : colors) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(color);
            childrenList2.add(cd);
        }
        fb2.setChildren(childrenList2);

        FiltrateBean fb3 = new FiltrateBean();
        fb3.setTypeName("电压等级");
        List<FiltrateBean.Children> childrenList3 = new ArrayList<>();
        for (String aCompany : company) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(aCompany);
            childrenList3.add(cd);
        }
        fb3.setChildren(childrenList3);

        FiltrateBean fb4 = new FiltrateBean();
        fb4.setTypeName("时间先后");
        List<FiltrateBean.Children> childrenList4 = new ArrayList<>();
        for (String time : times) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(time);
            childrenList4.add(cd);
        }
        fb4.setChildren(childrenList4);

        dictList.add(fb1);
        dictList.add(fb2);
        dictList.add(fb3);
        dictList.add(fb4);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //本地项目
            case R.id.two_local:
                try {
                    two_viewPager.setCurrentItem(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                two_editText.setText("");
                two_local.setTextColor(Color.rgb(255, 255, 255));
                two_online.setTextColor(Color.rgb(51, 51, 51));
                two_local.setBackgroundResource(R.drawable.btn_shape);
                two_online.setBackgroundResource(R.drawable.btn_shape_white);
                initData();
                adapter = new MainAdapter(getContext(), list);
                two_listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                break;
            //在线项目
            case R.id.two_online:
                two_viewPager.setCurrentItem(1);
                two_editText.setText("");
                two_online.setTextColor(Color.rgb(255, 255, 255));
                two_local.setTextColor(Color.rgb(51, 51, 51));
                two_local.setBackgroundResource(R.drawable.btn_shape_white);
                two_online.setBackgroundResource(R.drawable.btn_shape);
                setRecycleView(getContext(), MyApplication.getInstances().getOnlineDao().queryBuilder().where(OnlineDao.Properties.Phr.eq(SPUtils.getInstance().getString("usersId"))).list());
                break;
            //综合排序
            case R.id.two_zonghe:
                try {
                    list = MyApplication.getInstances().getItemsDao().queryBuilder().orderAsc(ItemsDao.Properties.Id).build().list();
                    MainAdapter mainAdapter = new MainAdapter(getContext(), list);
                    two_listView.setAdapter(mainAdapter);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            //时间排序
            case R.id.two_shijian:
                onResume();
                break;
            //搜索
            case R.id.two_ib_search:
                if (two_viewPager.getCurrentItem() == 0) {
                    MainAdapter mainAdapter1 = new MainAdapter(getContext(), listItems1);

                    two_listView.setAdapter(mainAdapter1);

                }/* else {
                    //MainsAdapter mainAdapter2 = new MainsAdapter(getContext(), listItems);

                    //listView.setAdapter(mainAdapter2);
                }*/
                break;
            //管理
            case R.id.activity_tv_save:
                if (DIALOG_BOTTOM) {
                    DIALOG_BOTTOM = false;
                    activity_tv_save.setText("关闭");
                    two_linear.setVisibility(View.VISIBLE);
                    initDialog();
                    two_cb_check.setChecked(false);
                    onResume();
                } else {
                    DIALOG_BOTTOM = true;
                    two_linear.setVisibility(View.GONE);
                    activity_tv_save.setText("管理");
                    for (int i = 0; i < list.size(); i++) {
                        //这如果使用第一种方法会修改不了数据，也不尝试全使用这个了，等有时间了试试。
                        Items items = list.get(i);
                        items.setBatchCheck(0);
                        MyApplication.getInstances().getItemsDao().update(items);
                    }
                    onResume();
                }
                break;
            //增加
            case R.id.activity_iv_add:
                Intent intent = new Intent(getContext(), AddItemActivity.class);
                intent.putExtra("add_id", 2);
                startActivity(intent);
                break;
        }
    }


    private void listOnClick() {
        two_listView.setOnItemClickListener((parent, view, position, id) -> {
            Items items = (Items) adapter.getItem(position);

            if (items.getState().equals("在线")) {
                //getToast(context, items.getName() + items.getId() + items.isCheck());
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();

                map.put("surverytaskid", items.getProjectId());


                String result = HttpConfig.callService("getProjectStatusInfo", map);
                ////Log.e("TAG", "沛星:     " + items.getProjectId() + "    " + result);

                if (parseXMLWithPulls(result)) {
                    ToastUtils.showShort("此项目已结束勘测");
                } else {
                    Intent intent = new Intent(getContext(), MapActivity.class);
                    intent.putExtra("name", items.getState());
                    intent.putExtra("id", items.getId());
                    startActivity(intent);
                }
            } else {
                Intent intent = new Intent(getContext(), MapActivity.class);
                intent.putExtra("name", items.getState());
                intent.putExtra("id", items.getId());
                startActivity(intent);
            }

        });
    }


   /* private void onLoad() {
        listView.stopRefresh();//停止刷新
        @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("MM-ddHH:mm:ss");//设置日期显示格式
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);// 将时间装换为设置好的格式
        listView.setRefreshTime(str);//设置时间
    }
*/

    /**
     * 删除设备对话框
     */
    private void startDialog(final long cid, final String name, final String state, final String type) {


        final NormalDialog dialog = new NormalDialog(getContext());
        dialog.content("您确定要删除吗?")//
                .style(NormalDialog.STYLE_TWO)//
                .btnNum(2)
                .title("删除提示")
                .btnText("取消", "删除")//
                .show();
        dialog.setOnBtnClickL(
                dialog::dismiss, () -> {
                    dialog.dismiss();
                    if (state.equals("在线")) {
                        Online online = MyApplication.getInstances().getOnlineDao().queryBuilder().where(OnlineDao.Properties.Id.eq(type)).list().get(0);
                        online.setDown("no");
                        MyApplication.getInstances().getOnlineDao().update(online);
                        deleteItem(cid, name);
                    } else {
                        deleteItem(cid, name);
                    }

                });

    }

    /**
     * 删除项目
     * @param cid 项目id
     * @param name 项目名称
     */
    private void deleteItem(long cid, String name) {
        MyApplication.getInstances().getItemsDao().deleteByKey(cid);
        List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();
        for (int j = 0; j < pointsList.size(); j++) {
            MyApplication.getInstances().getPointsDao().delete(pointsList.get(j));
            try {
                List<Equipment> equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(pointsList.get(j).getId())).build().list();
                if (equipmentList.size() > 0)
                    for (int i = 0; i < equipmentList.size(); i++) {
                        MyApplication.getInstances().getEquipmentDao().delete(equipmentList.get(i));
                    }
                List<Photos> photosList = MyApplication.getInstances().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(pointsList.get(j).getId())).build().list();
                if (photosList.size() > 0)
                    for (int i = 0; i < photosList.size(); i++) {
                        MyApplication.getInstances().getPhotosDao().delete(photosList.get(i));
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<Line> lines = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(cid)).build().list();
        try {
            for (int z = 0; z < lines.size(); z++) {
                MyApplication.getInstances().getLineDao().delete(lines.get(z));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name);

        initData();
        onResume();
        adapter = new MainAdapter(getContext(), list);
        two_listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @SuppressLint("CommitTransaction")
    @Override
    public void onDestroy() {
        super.onDestroy();
        TwoFragment fragment = new TwoFragment();
        FragmentManager manager = getFragmentManager();
        assert manager != null;
        FragmentTransaction transaction = manager.beginTransaction();
        manager.beginTransaction().remove(fragment);
        transaction.hide(fragment);
    }

    /**
     * 写在外面没法刷新试图
     **/
    private class MainAdapter extends BaseAdapter {
        @SuppressLint("SdCardPath")
        private final Context context;
        private final List<Items> list;
        private boolean isCheck = true;

        MainAdapter(Context context, List<Items> list) {
            this.context = context;
            this.list = list;
        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint({"InflateParams", "SetTextI18n"})
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.activity_two_list, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else
                viewHolder = (ViewHolder) convertView.getTag();
            final Items items = list.get(position);
            if (!DIALOG_BOTTOM) {
                viewHolder.main_cb_switch.setVisibility(View.VISIBLE);
            } else {
                viewHolder.main_cb_switch.setVisibility(View.GONE);
            }
            if (items.getBatchCheck() == 1) {
                viewHolder.main_cb_switch.setChecked(true);
            } else {
                viewHolder.main_cb_switch.setChecked(false);
            }
            viewHolder.main_cb_switch.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isChecked) {
                    items.setBatchCheck(1);
                    MyApplication.getInstances().getItemsDao().update(items);
                } else {
                    items.setBatchCheck(0);
                    MyApplication.getInstances().getItemsDao().update(items);
                }
            });
            viewHolder.main_tv_name.setText(items.getName() + "");
            viewHolder.main_tv_note.setText(items.getType() + "  " + items.getVoltage());
            viewHolder.main_tv_time.setText(items.getTime() + "");
            if ("在线".equals(items.getState())) {
                viewHolder.main_iv.setBackgroundResource(R.drawable.zaixian);
                ExportUnit exportUnit = new ExportUnit();
                viewHolder.main_tv_upload.setOnClickListener(v13 -> exportUnit.SetLocalExport(context, items.getId(), items.getName()));
                viewHolder.main_tv_up.setVisibility(View.VISIBLE);
                viewHolder.main_tv_up.setOnClickListener(view -> exportUnit.SetExport(context, items.getId(), items.getName()));
            } else {
                viewHolder.main_iv.setBackgroundResource(R.drawable.bendi);
                ExportUnit exportUnit = new ExportUnit();
                viewHolder.main_tv_upload.setOnClickListener(v13 -> exportUnit.SetLocalExport(context, items.getId(), items.getName()));
                viewHolder.main_tv_up.setVisibility(View.GONE);
            }


            viewHolder.main_ibt_details.setOnClickListener(v -> {
                if (isCheck) {
                    viewHolder.main_ibt_details.setImageResource(R.drawable.xiala);
                    viewHolder.bellow_layout.setVisibility(View.VISIBLE);
                    viewHolder.main_tv_details.setOnClickListener(v1 -> {
                        if (items.getIsCheck()) {

                            Intent intent = new Intent(getActivity(), DetailsActivity.class);
                            intent.putExtra("details", items.getId());
                            intent.putExtra("de_id", 2);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(getActivity(), OnlineDetailsActivity.class);
                            intent.putExtra("details", items.getId());
                            intent.putExtra("de_id", 2);
                            startActivity(intent);
                        }

                    });
                    viewHolder.main_tv_delete.setOnClickListener(v12 -> startDialog(items.getId(), items.getName(), items.getState(), items.getType()));

                    isCheck = !isCheck;
                } else {
                    viewHolder.main_ibt_details.setImageResource(R.drawable.jinru);
                    viewHolder.bellow_layout.setVisibility(View.GONE);
                    isCheck = !isCheck;
                }
            });
            return convertView;
        }


        class ViewHolder {
            private TextView main_tv_name;
            private TextView main_tv_note;
            private ImageButton main_ibt_details;
            private TextView main_tv_time;
            private RelativeLayout bellow_layout;
            private TextView main_tv_upload;
            private TextView main_tv_up;
            private TextView main_tv_delete;
            private TextView main_tv_details;
            private CheckBox main_cb_switch;
            private ImageView main_iv;

            ViewHolder(View rootView) {
                this.main_tv_name = rootView.findViewById(R.id.main_tv_name);
                this.main_tv_note = rootView.findViewById(R.id.main_tv_note);
                this.main_ibt_details = rootView.findViewById(R.id.main_ibt_details);
                this.main_tv_time = rootView.findViewById(R.id.main_tv_time);
                this.bellow_layout = rootView.findViewById(R.id.below_layout);
                this.main_tv_upload = rootView.findViewById(R.id.main_tv_upload);
                this.main_tv_up = rootView.findViewById(R.id.main_tv_up);
                this.main_tv_delete = rootView.findViewById(R.id.main_tv_delete);
                this.main_tv_details = rootView.findViewById(R.id.main_tv_details);
                this.main_cb_switch = rootView.findViewById(R.id.main_cb_switch);
                this.main_iv = rootView.findViewById(R.id.main_iv);
            }

        }


    }

}
